package com.fh.shop.admin.interceptor;

import com.fh.shop.admin.common.SystemContant;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LoginInterceptor extends HandlerInterceptorAdapter {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取session中存入的值
        Object user = request.getSession().getAttribute(SystemContant.CURR_USER);
        //判断是否为空，为空则拦截，重定向到登录页面
        if (user == null) {
            //获取请求头
            String header = request.getHeader("X-Requested-With");
            //判断请求头的值是否正确来确认是否为ajax请求
            if (StringUtils.isNotEmpty(header) && header.equalsIgnoreCase("XMLHttpRequest")) {
                //成功说明是ajax请求，那么给客户端自定义一个响应头
                response.addHeader("fh-ajax-timeout", "timeout");
            } else {
                //否则说明是普通请求跳转到登录页面
                response.sendRedirect(SystemContant.LOGIN_PAGE);
            }
            return false;
        } else {
            //不为空则放开当前请求
            return true;
        }

    }
}
